/*
Copyright SecureKey Technologies Inc. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package balanced

import (
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/common/balancer"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/common/logging"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/ichain/events/client/inoderesolver"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/context"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/ichain"
)

var logger = logging.NewLogger("ichainsdk/ichain")

// InodeResolver 选择inode节点注册事件
type InodeResolver struct {
	balance balancer.Balancer
}

func NewResolver() inoderesolver.Provider {
	return func(context context.Client, chainID string) inoderesolver.Resolver {
		return New(context, chainID)
	}
}

func New(context context.Client, chainID string) *InodeResolver {
	balance := balancer.GetBalancer(context.EndpointConfig().ChainConfig(chainID).Policies.EventService)

	logger.Debugf("Creating new balanced inode resolver")

	return &InodeResolver{
		balance: balance,
	}
}

func (r *InodeResolver) Resolve(inodes []ichain.Inode) (ichain.Inode, error) {
	return r.balance.Choose(inodes)
}
